﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XbsWebAPI.Application;
using XbsWebAPI.Application.CheckInOut;
using XbsWebAPI.Application.Detaileds;
using XbsWebAPI.Application.Feedback;
using XbsWebAPI.Application.OrderFinance;
using XbsWebAPI.Application.SystemAdmin;
using XbsWebAPI.Core.Repositories;
using XbsWebAPI.Core.Repositories.Detaileds;
using XbsWebAPI.Core.Repositories.Feedback;
using XbsWebAPI.Core.Repositories.SystemAdmin;
using XbsWebAPI.EntityFrameworkCore;
using XbsWebAPI.EntityFrameworkCore.Entities;
using XbsWebAPI.MainHost.Tools;

namespace XbsWebAPI.MainHost
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //注册跨域请求CORS服务
            services.AddCors(options =>
            {
                options.AddPolicy("AllowCors", builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod();
                });
            });

            //增加鉴权认证
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = new Microsoft.AspNetCore.Http.PathString("/Admin/Login");
                });

            services.AddDbContextPool<DataContext>(options => options.UseMySql(Configuration.GetConnectionString("XbsDBConnection"), new MySqlServerVersion(new Version(8, 0, 28))));

            //services.AddIdentity<IdentityUser,IdentityRole>().AddEntityFrameworkStores<DataContext>();
            services.AddIdentity<XbsAdminUser, IdentityRole>()
                .AddEntityFrameworkStores<DataContext>()
                .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequiredLength = 6;
                options.Password.RequiredUniqueChars = 3;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;
            });

            services.AddControllers();

            services.AddScoped<ICampAppService, CampAppService>();
            services.AddScoped<IHouseTypeAppService, HouseTypeAppService>();
            services.AddScoped<ISupportingFacilityAppService, SupportingFacilityAppService>();
            services.AddScoped<IGuestAppService, GuestAppService>();
            services.AddScoped<IMiniProgramAppService, MiniProgramAppService>();
            services.AddScoped<IRoomAppService, RoomAppService>();
            services.AddScoped<IRoomStatusAppService, RoomStatusAppService>();
            services.AddScoped<IMenuAppService, MenuAppService>();
            services.AddScoped<ICheckInAppService, CheckInAppService>();
            services.AddScoped<ISystemRoleAppService, SystemRoleAppService>();
            services.AddScoped<IXbsAdminUserAppService, XbsAdminUserAppService>();
            services.AddScoped<IFeedBackAppService, FeedBackAppService>();
            services.AddScoped<IOrderAppService, OrderAppService>();
            services.AddScoped<IRoomStatusAppService, RoomStatusAppService>();
            services.AddScoped<IDetailedAppService, DetailedAppService>();
            services.AddScoped<ICheckOutAppService, CheckOutAppService>();


            services.AddScoped<ICampRepository, CampRepository>();
            services.AddScoped<IHouseTypeRepository, HouseTypeRepository>();
            services.AddScoped<ISupportingFacilityRepository, SupportingFacilityRepository>();
            services.AddScoped<IHouseTypeHolidayRepository, HouseTypeHolidayRepository>();
            services.AddScoped<IHouseTypeSpecialDayRepository, HouseTypeSpecialDayRepository>();
            services.AddScoped<IGuestRepository, GuestRepository>();
            services.AddScoped<IMiniProgramRepository, MiniProgramRepository>();
            services.AddScoped<IMiniProgramImageRepository, MiniProgramImageRepository>();
            services.AddScoped<ICheckInRepository, CheckInRepository>();
            services.AddScoped<IRoomRepository, RoomRepository>();
            services.AddScoped<IMenuRepository, MenuRepository>();
            services.AddScoped<ICheckInRepository, CheckInRepository>();
            services.AddScoped<ISystemRoleRepository, SystemRoleRepository>();
            services.AddScoped<IXbsAdminUserRepository, XbsAdminUserRepository>();
            services.AddScoped<IGuestRecordRepository, GuestRecordRepository>();
            services.AddScoped<IFeedBackRepository, FeedBackRepository>();
            services.AddScoped<IOrderRepository, OrderRepository>();
            services.AddScoped<IRoomStatusRepository, RoomStatusRepository>();
            services.AddScoped<IDetailedRepository,DetailedRepository>();
            services.AddScoped<ICheckOutRepository, CheckOutRepository>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                    new OpenApiInfo
                    {
                        Title = Configuration["XbsConfig:SwaggerUI:OpenApiInfo:Title"],
                        Version = Configuration["XbsConfig:SwaggerUI:OpenApiInfo:Version"]
                    });
                var rootDir = Configuration["XbsConfig:SwaggerUI:Path:RootDir"];
                var hostPath = Configuration["XbsConfig:SwaggerUI:Path:MainHost"];
                var efCorePath = Configuration["XbsConfig:SwaggerUI:Path:EntityFrameworkCore"];
                var applicationPath = Configuration["XbsConfig:SwaggerUI:Path:Application"];
                var path = System.Environment.CurrentDirectory;
                if (path.Contains("XbsWebAPI.MainHost"))
                {
                    path = path.Replace("XbsWebAPI.MainHost", "");
                }
                c.IncludeXmlComments(path + efCorePath);
                c.IncludeXmlComments(path + applicationPath);
            });

            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.AddAutoMapper(typeof(DomainToViewModelMappingProfile));
            services.AddAutoMapper(typeof(ViewModelToDomainMappingProfile));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //启用Cors中间件
            app.UseCors("AllowCors");

            //AddFile()方法是Serilog.Extensions.Logging.File中提供的扩展方法
            loggerFactory.AddFile("Logs/log{Date}.txt");

            WebPath.Path = env.WebRootPath;

            app.UseStaticFiles();

            app.UseHttpsRedirection();

            app.UseRouting();

            //鉴权
            app.UseAuthentication();

            //授权
            //app.UseAuthorization();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                //swagger设置为折叠
                c.DocExpansion(DocExpansion.None);
                c.SwaggerEndpoint("/swagger/v1/swagger.json", Configuration["XbsConfig:SwaggerUI:OpenApiInfo:Title"]);
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
